'use strict';
const fiip = require('fiip');
const Link = fiip.Link;

const startClient = (ip, port, arg) => {
  const io = require('socket.io-client');
  const rlink = new Link.Client();
  rlink.type = Link.type.websocket;
  rlink.status = Link.status.client;
  rlink.address = ip;
  rlink.port = port;
  rlink.fd = io(`${ip}:${port}?${arg}`);
  rlink.send = (data, dataLen, link) => {
    const d = data.slice(0, dataLen).toString('hex');
    rlink.fd.emit('fiipData', d);
  };
  rlink.recv = fiip.recv.bind(fiip);

  rlink.fd.on('fiipData', (data) => {
    data = Buffer.from(data, 'hex');
    rlink.recv(data, data.length, rlink);
  });
  rlink.fd.on('connect', () => {
    console.debug('fiip-link-websocket/client: connect');
  });
  rlink.fd.on('error', (error) => {
    console.error('fiip-link-websocket/client: error:', error);
  });
  rlink.fd.on('disconnect', (reason) => {
    console.error('fiip-link-websocket/client: disconnect:', reason);
  });

  return rlink;
};

module.exports = startClient;
